/*
* $Id: DeviceSyncForm.java 277 2011-03-02 00:42:20Z volok-aleksej@yandex.ru $
*
* Copyright 2008-2011 by Volokitin Alexey
* All rights reserved
*
*/
package apiary.ui;

import apiary.Apiary;
import apiary.bt.BluetoothConnector;
import apiary.common.FormHelper;
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.RemoteDevice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;

public class DeviceSyncForm extends BackScreen implements CommandListener,
                                                          ItemStateListener,
                                                          ItemEventListener
{
    private CategoryItem curSel;
    private Image img;
    private Vector devices;

    public DeviceSyncForm() {
        super("");
        Init();
    }
    public DeviceSyncForm(String name) {
        super(name);
        Init();
    }

    public void setData(Vector data) {
        devices = data;
        for(int i = 0; i < data.size(); i++) {
            try {
                RemoteDevice device = (RemoteDevice) data.elementAt(i);
                CategoryItem item = FormHelper.createCategoryItem(this, String.valueOf(i),
                        device.getFriendlyName(false), "/res/Bluetooth.png");
                append(item);
            } catch (IOException ex) {}
        }
    }

    public void commandAction(Command c, Displayable d) {
        Apiary apiary = Apiary.getInstance();
        if(c.getCommandType() == Command.OK) {
            OnOk();
            apiary.Display(backForm);
        } else if (c.getCommandType() == Command.BACK)
            apiary.Display(backForm);
    }

    public void itemStateChanged(Item item) {
        CategoryItem category = (CategoryItem)item;
        if(category.getActive())
            SetCurSel((CategoryItem)item);
    }

    public void itemNotifyEvent(Item item, String event) {
        if(event.equals(ItemEventListener.PRESS)){
            SetCurSel((CategoryItem)item);
            OnOk();
        }
    }

    protected void SetCurSel(CategoryItem item){
        if(item == curSel)
            return;
        curSel = item;
    }
    private void OnOk() {
        int id = Integer.parseInt(curSel.getId());
        RemoteDevice device = (RemoteDevice) devices.elementAt(id);
        BluetoothConnector connector = new BluetoothConnector(device);
        Apiary.getInstance().Display(connector, backForm);
    }

    private void Init() {
        Apiary apiary = Apiary.getInstance();
        curSel = null;

        setCommandListener(this);
        setItemStateListener(this);

        addCommand(new Command(apiary.getLocaleString("Back"), Command.BACK, 0));
        addCommand(new Command(apiary.getLocaleString("Synchronize"), Command.OK, 0));
    }
}

